package com.iris.live.services.report.sources;

import com.iris.live.services.common.JsonObjectUtils;
import com.iris.live.services.common.NumberUtils;
import com.iris.live.services.data.repositories.ReportRepository;
import com.iris.live.services.report.Cell;
import com.iris.live.services.report.Row;
import com.iris.live.services.report.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by HangLiu on 2017/1/12.
 */
@Component("FiPerformanceTrackingSource")
public class FiPerformanceTrackingSource extends AbstractReportSourceService {
    private static final Logger logger = LoggerFactory.getLogger(FiPerformanceTrackingSource.class);

    //7-9, 23-32,62, 65-66，68-99
    private static final int [] isHidden = {
            7,8,9,
            23,24,25,26,27,28,29,30,31,32,
            62,
            65,66,
            68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99 };
    private static final String[] indicators = {
            "MB_actualRetailRos", "SMART_actualRetailRos",
            "","","","","",
            "formular","MB_newCarInsurance", "SMART_newCarInsurance",
            "insurancePremium","MB_firstYearInsurancePremium", "SMART_firstYearInsurancePremium", "newCarInsuranceCommission",
            "formular","formular","formular",
            "","","","","","","","","","","","","",
            "formular","MB_newCarFinancing", "SMART_newCarFinancing", "MB_newCarAgility", "SMART_newCarAgility",
            "formular","MB_financingCommission", "SMART_financingCommission",
            "formular","MB_financingServiceFeeMargin", "SMART_financingServiceFeeMargin",
            "formular","MB_financingAmount", "SMART_financingAmount",
            "formular","formular","formular","formular","formular","formular","formular","formular",
            "formular","formular","formular",
            "","","",
            "formular","formular",
    };

    @Autowired
    private ReportRepository reportRepository;

    @Override
    public List<Row> getSheetRows(Map<String, Object> context, Sheet sheet) {
        Map values = getDataReport(context.get("permit").toString(), context.get("year").toString());
        List<Row> rows = new ArrayList<>();

        logger.warn(JsonObjectUtils.writeAsJson(values));


        rows.add(new Row());
        Cell[] cells = new Cell[1];
        cells[0] = new Cell(sheet.getName(), 1);
        rows.add(new Row(cells));
        rows.add(new Row());
        rows.add(new Row());

        for (String indicator : indicators) {
            if (indicator == null || "".equals(indicator)) {
                rows.add(new Row());
            } else if (indicator.equals("formular")) {
                rows.add(new Row(true));
            } else {
                rows.add(new Row(getCells(values, indicator)));
            }
        }
        //设置隐藏属性为true
        if(rows.size()>=isHidden[isHidden.length-1]) {
            for (int i = 0; i < isHidden.length; i++) {
                rows.get(isHidden[i] - 1).setHidden(true);
            }
        }
        return rows;
    }

    private Cell[] getCells(Map values, String indicator) {
        Cell[] cells = new Cell[12];
        String value = null;

        for (int index = 1; index <= 12; index++) {
            Object o = values.get(indicator + "_" + (index > 9 ? index : "0" + index));
            value = (o == null ? "0" : o).toString();
            cells[index - 1] = new Cell(value, "double", 1 + index);
        }

        return cells;
    }

    private Map getDataReport(String type, String year) {
        Map map = new HashMap();
        try {
            List list = getReportByPermitAndYear(type, year);
            String key = null;
            Double financingCommission = 0d, financingServiceFee = 0d, insuranceCommission = 0d,
                   insurancePremium = 0d,  firstYearInsurancePremium = 0d, newCarAgility=0d;

            for (Object o : list) {
                Map m = (Map) o;

                //新保总手续费

                insuranceCommission = NumberUtils.round(Double.valueOf(getValue(m, "NEW_CAR_INSURANCE_COMMISSION")) * 1.17,2);
                financingCommission = NumberUtils.round(Double.valueOf(getValue(m, "FINANCING_COMMISSION")) * 1.17, 2);
                financingServiceFee = NumberUtils.round(Double.valueOf(getValue(m, "FINANCING_SERVICE_FEE_MARGIN")) * 1.06, 2);
                firstYearInsurancePremium = NumberUtils.round(Double.valueOf(getValue(m, "FIRST_YEAR_COMMERCIAL_INSURANCE_PREMIUM")), 2) + NumberUtils.round(Double.valueOf(getValue(m, "FIRST_YEAR_COMPULSORY_INSURANCE_PREMIUM")), 2);
                insurancePremium = NumberUtils.round(Double.valueOf(getValue(m, "COMPULSORY_INSURANCE_PREMIUM")), 2) + NumberUtils.round(Double.valueOf(getValue(m, "COMMERCIAL_INSURANCE_PREMIUM")), 2);

                newCarAgility = NumberUtils.roundInt(Double.valueOf(getValue(m,"NEW_CAR_AGILITY")));

                key = "newCarInsuranceCommission_" + m.get("STAT_MONTH");
                if(! map.containsKey(key)) {
                    map.put(key, insuranceCommission);
                }else{
                    map.put(key, NumberUtils.round(getValue(map, key),2) + insuranceCommission);
                }

                key = "insurancePremium_" + m.get("STAT_MONTH");
                if(! map.containsKey(key)) {
                    map.put(key, insurancePremium);
                }else{
                    map.put(key, NumberUtils.round(getValue(map, key),2) + insurancePremium);
                }

                if("smart".equalsIgnoreCase(m.get("MODEL").toString())){
                    map.put("SMART_newCarAgility_" + m.get("STAT_MONTH"), newCarAgility);
                    map.put("SMART_actualRetailRos_" + m.get("STAT_MONTH"), m.get("ACTUAL_RETAIL_ROS"));
                    map.put("SMART_newCarInsurance_" + m.get("STAT_MONTH"), m.get("NEW_CAR_INSURANCE"));
                    map.put("SMART_financingAmount_" + m.get("STAT_MONTH"), m.get("FINANCING_AMOUNT"));
                    map.put("SMART_financingCommission_" + m.get("STAT_MONTH"), financingCommission);
                    map.put("SMART_financingServiceFeeMargin_" + m.get("STAT_MONTH"), financingServiceFee);
                    map.put("SMART_newCarFinancing_" + m.get("STAT_MONTH"), m.get("NEW_CAR_FINANCING"));
                    map.put("SMART_firstYearInsurancePremium_" + m.get("STAT_MONTH"), firstYearInsurancePremium);
                }else{
                    //ROS
                    key = "MB_actualRetailRos_" + m.get("STAT_MONTH");
                    if(! map.containsKey(key)){
                        map.put(key, m.get("ACTUAL_RETAIL_ROS"));
                    }else{
                        map.put(key, NumberUtils.round(Double.valueOf(getValue(m, "ACTUAL_RETAIL_ROS")),0) + NumberUtils.roundInt(getValue(map, key)));
                    }

                    //先享后选台数
                    key = "MB_newCarAgility_" + m.get("STAT_MONTH");
                    if(! map.containsKey(key)){
                        map.put(key, newCarAgility);
                    }else{
                        map.put(key, newCarAgility + NumberUtils.roundInt(getValue(map, key)));
                    }

                    //新保台数
                    key = "MB_newCarInsurance_" + m.get("STAT_MONTH");
                    if(! map.containsKey(key)){
                        map.put(key, m.get("NEW_CAR_INSURANCE"));
                    }else{
                        map.put(key,NumberUtils.roundInt(getValue(m, "NEW_CAR_INSURANCE")) + NumberUtils.roundInt(getValue(map, key)));
                    }

                    //首年保费
                    key = "MB_firstYearInsurancePremium_" + m.get("STAT_MONTH");
                    if(! map.containsKey(key)){
                        map.put(key, firstYearInsurancePremium);
                    }else{
                        map.put(key, firstYearInsurancePremium + NumberUtils.round(getValue(map, key), 2));
                    }

                    //新车金融台数
                    key = "MB_newCarFinancing_" + m.get("STAT_MONTH");
                    if(! map.containsKey(key)){
                        map.put(key, m.get("NEW_CAR_FINANCING"));
                    }else{
                        map.put(key, NumberUtils.roundInt(getValue(m, "NEW_CAR_FINANCING")) + NumberUtils.roundInt(getValue(map, key)));
                    }

                    //金融手续费
                    key = "MB_financingCommission_" + m.get("STAT_MONTH");
                    if(! map.containsKey(key)){
                        map.put(key, financingCommission);
                    }else{
                        map.put(key, financingCommission + NumberUtils.round(getValue(map, key),2));
                    }

                    //金融服务费
                    key = "MB_financingServiceFeeMargin_" + m.get("STAT_MONTH");
                    if(! map.containsKey(key)){
                        map.put(key, financingServiceFee);
                    }else{
                        map.put(key, financingServiceFee + NumberUtils.round(getValue(map, key),2));
                    }

                    //贷款总额
                    key = "MB_financingAmount_" + m.get("STAT_MONTH");
                    if(! map.containsKey(key)){
                        map.put(key, m.get("FINANCING_AMOUNT"));
                    } else {
                        map.put(key, NumberUtils.round(getValue(m, "FINANCING_AMOUNT"),2) + NumberUtils.round(getValue(map, key),2));
                    }
                }
            }
        } catch (Exception e) {
            logger.error("导出F&I报表异常", e);
        }

        return map;
    }

    private String getValue(Map value, String key){
        return value.containsKey(key) && value.get(key) != null ? value.get(key).toString() : "0";
    }

    private List getReportByPermitAndYear(String type, String year) {
        return reportRepository.getSaleManagementReportByPermitAndYear(type, year);
    }
}
